<template>
	<view class="bindingCards-con">
		<view class="bindingCards-ul-bg"></view>
		<view class="bindingCards-ul p_rlt">
			<view class="err-style flex justify-between align-center" v-if="errText">
				<view>
					<text class="lg text-gray cuIcon-infofill cuIcon-infofill-style"
						:class="abnormalFlag ?' err-red':''"></text>
					<text class="err-font-c" :class="abnormalFlag ?' err-red':''">{{errText}}</text>
				</view>
				<view v-if="errPhoneFlag" @click="toRouter('/pages/user/openVip/openVip')">
					<text class="err-font-green">去开卡</text>
					<text class="lg text-gray cuIcon-right cuIcon-right-style"></text>
				</view>
			</view>
			<view class="bindingCards-li" @click="btnFocus('isNameFocused')">
				<text class="bindingCards-lable font-de-size">手机号</text>
				<view class="bindingCards-input">
					<input type="number" maxlength="11" class="uni-input font-de-size" :focus="nameFocus"
						@input="phoneInput" @blur="onblur('isNameFocused')" v-model="bindParam.mobile"
						placeholder="请输入手机号" placeholder-class="placeholderStyle" />
				</view>
				<view class="bindingCards-line" :class="{ 'bindingCardsLine': nameFocus }"></view>
			</view>
			<view class="bindingCards-li" @click="btnFocus('isCodeFocused')">
				<text class="bindingCards-lable font-de-size padding-tb-sm">验证码</text>
				<view class="bindingCards-input">
					<input type="number" maxlength="6" class="uni-input font-de-size" @blur="onblur('isCodeFocused')"
						:focus="codeFocus" v-model="bindParam.code" placeholder="请输入6位验证码"
						placeholder-class="placeholderStyle" />
				</view>
				<text class="get-code-style padding-tb-sm point" @click.stop="handleGetCode"
					:class="{ errColor: disCode }">{{ buttonText }}</text>
				<view class="bindingCards-line" :class="{ 'bindingCardsLine': codeFocus }"></view>
			</view>
			<view class="bindingCards-li" @click="btnFocus('isPwdFocused')">
				<text class="bindingCards-lable font-de-size padding-tb-sm">支付密码</text>
				<view class="bindingCards-input"><input class="uni-input font-de-size" maxlength="6"
						:password="passwordFlag" :focus="pwdFocus" v-model="bindParam.password" placeholder="请输入6位数密码"
						@blur="onblur('isPwdFocused')" placeholder-class="placeholderStyle" /></view>
				<text class="lg text-gray  posi-icon" :class="showPassword ?'cuIcon-attentionfill':'cuIcon-attention'"
					@click="showPassWord"></text>
				<view class="bindingCards-line" :class="{ 'bindingCardsLine': pwdFocus }"></view>
			</view>
			<view class="flex  justify-end">
				<text class="forgot-pwd" @click="toPwdReser">忘记密码?</text>
			</view>
		</view>
    <!-- <view class="mealis-con" v-if="orderType == 'meals'">
      <view class="flex justify-between con-w ul-con">
        <text>我同意自动约餐扣款</text>
        <switch color="#53A87F" style="transform:scale(0.9)" :checked="switchFlag"  @change="changeSwitch"/>
      </view>
      <view class="text-con">
        <text class="fcon-tixing"></text>
        <text>绑定成功后，约餐从此卡按实际金额自动扣款，卡内余额可以在颐而康连锁门店，颐而康精选商城，炖大侠进行消费。</text>
      </view>
    </view> -->
		<block>
			<view v-if="abnormalFlag" class="bindingCards-footer point" :class="{ errFooter: abnormalFlag }">
				<text>请去线下门店找客服处理</text>
			</view>
			<!-- errText -->
			<view v-else class="bindingCards-footer point" @click="btnSub" :class="{ errFooter: !canSubmit  }">
				<text>绑定</text>
			</view>
		</block>
		<loading></loading>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed } from 'vue'
  import { onLoad } from "@dcloudio/uni-app";
	import mFormRule from "@/config/formRule";
	import mChecker from "@/utils/checker";
	import mApi from "@/utils/mapi";
	import { showLoading, hideLoading } from '@/utils/helper';
	import { onShow } from '@dcloudio/uni-app';
	import { sendVeryCode, bindCardApi } from '@/api/vmeitime-http/index.js'
	const bindParam = ref({
		mobile: "",
		code: "",
		password: "",
	})
	const showPassword = ref(true)
	const passwordFlag = ref(true)
	const errText = ref(null)
	const errPhoneFlag = ref(null)  //是否显示去开卡
	const abnormalFlag = ref(null)  //异常状态
	const buttonText = ref('获取验证码') //倒计时
	const countdown = ref(0)  //倒计时
	const disCode = ref(false)  //验证码禁用
	const nameFocus = ref(null) //绑定输入框的获取状态  姓名
	const codeFocus = ref(null) //验证码
	const pwdFocus = ref(null) //密码
  const switchFlag = ref(false) //约餐自动扣款
	const inputStatus = ref([false, false, false])
	// const showPasswordText = ref(true)
	// const btnText = ref('绑定')  //提交按钮
  const orderType = ref(null)
  onLoad((option:any) => {
    if(option){
      orderType.value = option.orderType
    }
  })
  //约餐自动扣款
  const changeSwitch = (e) => {
    switchFlag.value = e.detail
    console.log(e.detail,'---------------------',switchFlag.value)
  }
	const showPassWord = () => {
		showPassword.value = !showPassword.value
		passwordFlag.value = !passwordFlag.value
	}
	const onblur = (source : string = '') => {
		switch (source) {
			case 'isNameFocused':
				console.log('123')
				inputStatus.value[0] = true
				nameFocus.value = false
				break;
			case 'isCodeFocused':
				inputStatus.value[1] = true
				codeFocus.value = false
				break;
			case 'isPwdFocused':
				inputStatus.value[2] = true
				pwdFocus.value = false
				break;
			default:
				break;
		}
	}
	// 初始化异常状态
	const phoneInput = () => {
		errPhoneFlag.value = false//手机号暂未绑定电子卡
		abnormalFlag.value = false//电子卡异常
		disCode.value = false
		errText.value = ''
	}
	const canSubmit = computed(() => {
		let checkParam = mChecker.check(
			bindParam.value,
			mFormRule.bindCardRule
		);
		let allfocs = inputStatus.value.some(item => item == true);
		console.log('canSubmit', checkParam, mChecker, allfocs)
		errText.value = allfocs && !checkParam ? mChecker.error.msg : '';
		return checkParam;
	});
	// 提交表单
	const btnSub = async (isFlag : any) => {
		let checkParam = mChecker.check(
			bindParam.value,
			mFormRule.bindCardRule
		);
		console.log('checkSendCode', checkParam);
		if (!checkParam) {
			mApi.msg(mChecker.error.msg);
			return;
		}
		if (!canSubmit) {
			console.log('canSubmit+++', canSubmit)
			return
		}
		try {
			showLoading()
			let res = await bindCardApi({ phone: bindParam.value.mobile, verifCode: bindParam.value.code, pswd: bindParam.value.password })
			hideLoading()
			if (res.result) {
				bindParam.value.code = ''
				bindParam.value.mobile = ''
				bindParam.value.password = ''
				mApi.msg('绑定成功！')
				setTimeout(() => {
					uni.navigateBack()
				}, 600)
			} else {
				
				let errMsg = res.shortMessage || '绑定失败！';
				// 根据特定条件更新错误信息
				if (errMsg === '卡已锁定' || res.msgCode === '-1') {
					errMsg = '该卡为锁定状态，请前往最近的门店，联系客服进行解锁。感谢您的配合。';
					// errText.value = errMsg
				}
				mApi.msg(errMsg)
			}
		} catch (e) {
			hideLoading()
			console.error(e)
		}
	}
	onShow(() => {
		clearInterval(timer.value);
	})
	const timer = ref(null)
	//获取验证码
	const handleGetCode = async () => {

		if (disCode.value) return
		let checkSendCode = mChecker.check(
			bindParam.value,
			mFormRule.sendCodeRule
		);
		console.log('checkSendCode', checkSendCode);
		if (!checkSendCode) {
			mApi.msg(mChecker.error.msg);
			return;
		}
		if (!disCode.value) {
			countdown.value = 60;
			disCode.value = true
			buttonText.value = `${countdown.value}S`
			timer.value = setInterval(() => {
				countdown.value--;
				if (countdown.value <= 0) {
					disCode.value = false
					clearInterval(timer.value);
					buttonText.value = '获取验证码';
				} else {
					buttonText.value = `${countdown.value}S`;
				}
			}, 1000);
		}
		try {
			showLoading()
			let res = await sendVeryCode({ phone: bindParam.value.mobile,busType:'BIND_VERIF_CARD' })
			hideLoading()
			if (res.result) {
				mApi.msg('验证码发送成功！')
			} else {
				buttonText.value = '获取验证码';
				disCode.value = false
				clearInterval(timer.value);
				mApi.msg(res.shortMessage || '验证码发送失败！')
			}
		} catch (e) {
			console.error(e)
		}

		console.log('获取验证码')
	}

	const btnFocus = (isFlag : any) => {
		switch (isFlag) {
			case 'isNameFocused':
				console.log('123')
				nameFocus.value = true
				codeFocus.value = false
				pwdFocus.value = false
				break;
			case 'isCodeFocused':
				codeFocus.value = true
				nameFocus.value = false
				pwdFocus.value = false
				break;
			case 'isPwdFocused':
				pwdFocus.value = true
				nameFocus.value = false
				codeFocus.value = false
				break;
			default:
				break;
		}
	}

	const toRouter = (url : String) => {
		uni.navigateTo({
			url
		})
	}
	const isValidPhoneNumber = (phone : any) => {
		const phonePattern = /^1[3-9]\d{9}$/;
		return phonePattern.test(phone);
	};
	const toPwdReser = () => {
		const phone = isValidPhoneNumber(bindParam.value.mobile) ? bindParam.value.mobile : '';
		toRouter('/pages/user/passwordReset/passwordReset?phone=' + phone);
	};
</script>

<style lang="scss">
  .mealis-con{
    width: 675.054rpx;
    margin: 30rpx auto;
    .text-con{
      color: #999;
      text-align: justify;
      font-size: 28rpx;
      font-weight: 400;
      padding-top: 20rpx;
      .fcon-tixing{
        font-size: 24rpx;
        margin-right: 5rpx;
      }
    }
    .ul-con{
      padding: 44rpx 24rpx 34rpx;
      border-radius: 20rpx;
      background: #FFF;
      box-shadow: 0px 2px 18px 0px rgba(0, 0, 0, 0.08);
    }
  }
	.forgot-pwd {
		padding-top: 36rpx;
		color: #999;
		font-family: "Microsoft YaHei UI";
		font-size: 32rpx;
		font-style: normal;
		font-weight: 400;
		line-height: normal;
	}

	.input_bottom {
		border: 0 none;
		background-image:
			/* linear-gradient(#44dcfd,#44dcfd), */
			linear-gradient(#1f3144, #1f3144);
		background-size: 0px 2px, 100% 1px;
		background-repeat: no-repeat;
		background-position: center bottom;
		border: none;
		outline: none;
		transition: all .5s;

	}

	input[type="text"]:focus {
		background-size: 100% 2px, 100% 1px;
	}

	.bindingCards-ul-bg {
		width: 100%;
		height: 391.008rpx;
		flex-shrink: 0;
		background: #70DEB1;
	}

	.errFooter {
		background: #E4E4E4 !important;
		color: #333 !important;
	}

	.errColor {
		color: #999 !important;
	}

	.focused {
		border-bottom: 1px solid #56BF7A !important;
	}

	.bindingCards-ul {
		width: 675.054rpx;
		flex-shrink: 0;
		border-radius: 10px;
		background: #FFF;
		box-shadow: 0px 2px 18px 0px rgba(0, 0, 0, 0.08);
		margin: -320rpx auto 0;
		padding: 30rpx 28rpx 70rpx 28rpx;

		.err-red {
			color: #F00 !important;
		}

		.err-font-c {
			color: #FF9700;
			font-size: 28rpx;
			font-style: normal;
			font-weight: 400;
			line-height: normal;
		}

		.err-font-green {
			color: #148A3D;
			font-family: ABeeZee;
			font-size: 28rpx;
			font-style: normal;
			font-weight: 400;
			line-height: normal;
		}

		.cuIcon-right-style {
			color: #148A3D;
		}

		.cuIcon-infofill-style {
			color: #FF9700;
			margin-right: 10rpx;
		}

		.err-style {
			position: absolute;
			left: 28rpx;
			top: 20rpx;
			z-index: 6;
			width: 636rpx;
			height: 64rpx;
			flex-shrink: 0;
			border-radius: 8rpx;
			background: rgba(254, 180, 72, 0.15);
			padding: 0 16rpx;
		}

		.font-de-size {
			font-family: "Microsoft YaHei UI";
			font-size: 32rpx;
			font-weight: 400;
		}

		.bindingCards-li {
			display: flex;
			border-bottom: 1px solid #F3F3F3;
			padding-top: 70rpx;
			padding-bottom: 42rpx;
			position: relative;
			min-height: 160rpx;
			align-items: center;

			.bindingCardsLine {
				width: 100%;
				height: 2rpx;
				position: absolute;
				bottom: 0;
				flex-shrink: 0;
				stroke-width: 1px;
				background-color: #56BF7A;
				stroke: #56BF7A;
				filter: drop-shadow(0px 0px 4px #56BF7A);
				transition: all .5s;
			}

			.posi-icon {
				font-size: 35rpx;
			}

			.get-code-style {
				color: #148A3D;
				font-size: 32rpx;
				font-style: normal;
				font-weight: 400;
				line-height: normal;
				width: 160rpx;
				text-align: right;
				display: inline-block;
				// position: absolute;
				// right: 0;
				// text-align: right;
			}

			.placeholderStyle {
				color: #CBCBCB;
			}

			.bindingCards-input {
				flex: 1;
				padding-right: 30rpx;

				.uni-input {
					color: #333;
				}
			}

			.bindingCards-lable {
				width: 150rpx;
				color: #333;
			}
		}
	}

	.bindingCards-footer {
		width: 666.772rpx;
		height: 84rpx;
		flex-shrink: 0;
		border-radius: 20rpx;
		background: #53A87F;
		color: #FFF;
		text-align: center;
		font-size: 32rpx;
		font-weight: 400;
		position: fixed;
		bottom: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		left: 50%;
		transform: translateX(-50%);
	}
</style>